<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/9/2
 * Time: 15:13
 */
namespace App\Services;

use App\Repositories\UserLevelRelationsRepository;
use App\Repositories\UserRepository;

class UserLevelRelationsService
{
    protected $userLevelRelationsRepository;
    protected $userRepository;

    public function __construct(UserLevelRelationsRepository $userLevelRelationsRepository,
                                UserRepository $userRepository)
    {
        $this->userLevelRelationsRepository = $userLevelRelationsRepository;
        $this->userRepository = $userRepository;
    }

    /**
     * 根据第三个用户获取用户关系
     * @param $ThreeUserId
     * @return array
     */
    public function getUserLevelRelations($ThreeUserId)
    {
        $userLevelRelation = $this->userLevelRelationsRepository->first($ThreeUserId)->toArray();
        if (!empty($userLevelRelation)) {
            $relations['three'] = $userLevelRelation;
            //是否有上一级pid 0 顶级
            if (0 < $userLevelRelation['pid']) {
                $twoParent = $this->userLevelRelationsRepository->byId($userLevelRelation['pid'])->toArray();
                $relations['two'] = $twoParent;
                if (0 < $twoParent['pid']) {
                    $oneParent = $this->userLevelRelationsRepository->byId($twoParent['pid'])->toArray();
                    $relations['one'] = $oneParent;
                } else {
                    $relations['one'] = [];
                }
            } else {
                $relations['two'] = [];
            }
        } else {
            $relations = [];
        }
        return $relations;
    }

    /**
     * 邀请5个实名升级高级会员
     * @param $fromUserId
     */
    public function invitedAuthToLevel3($fromUserId)
    {
        //判断上一级是否需要升级为高级会员
        $currentUserLevelRelations = $this->userLevelRelationsRepository->first($fromUserId);
        //上一级是否为普通
        $upLevel = $this->userLevelRelationsRepository->first($currentUserLevelRelations->pid);
        if (!empty($upLevel)) {
            $num = $upLevel->name_number + 1;
            if ($num >= 5 && $upLevel->level_id > 3) {
                $this->userLevelRelationsRepository->updateUserLevelId($upLevel->user_id, 3);
                $this->userRepository->updateUserLevel($upLevel->user_id, 3);
            }
            $upLevel->update(['name_number' => $num, 'update_time' => time()]);
        }
    }
}